#!/usr/bin/python
import os, sys, string

class XXFileContentReplace:
	def __init__(self):
		pass
	
	def printHelp(self, cmd):
		print 'Please use the following cmd:'
		print '    ' + cmd + ' dir oldStr newStr'
		print '    ' + cmd + ' file oldStr newStr'
		print 'e.g.'
		print '    ' + cmd + ' /home/fkong/tmp 12345 54321'
		print '    ' + cmd + ' /home/fkong/build.xml 12345 54321' 
	
	def replaceByDir(self, dir, s1, s2):
		list = self.getList(dir)
		for i in range(0, len(list)):
			self.replaceByFile(str(list[i]), s1, s2)

	def replaceByFile(self, file, s1, s2):
		inputfile = file
		outputfile = file + '.0123456789'
		input = open(inputfile, 'r')
		output = open(outputfile, 'w')
		for s in input.xreadlines() :
			output.write(s.replace(s1, s2))
		input.close()
		output.close()
		os.rename(outputfile, inputfile)
		
	def getList(self, dir):
		list = []
		files = os.listdir(dir)
		for file in files:
			file = os.path.join(dir, file)
			if os.path.isdir(file):
				list += self.getList(file)
			else :
				list.append(file)
		return list
	
if len(sys.argv) != 4:
	t = XXFileContentReplace()
	t.printHelp(sys.argv[0])
else:
	t = XXFileContentReplace()
	sold = sys.argv[2]
	snew = sys.argv[3]
	if os.path.isdir(sys.argv[1]):
		t.replaceByDir(sys.argv[1], sold, snew)
	else:
		t.replaceByFile(sys.argv[1], sold, snew)
